package com.wangshuo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wangshuo.common.MenuHelper;
import com.wangshuo.config.Result;
import com.wangshuo.config.ResultCodeEnum;
import com.wangshuo.domain.SysMenu;
import com.wangshuo.domain.SysRoleMenu;
import com.wangshuo.model.vo.AssginMenuVo;
import com.wangshuo.service.SysMenuService;
import com.wangshuo.service.SysRoleMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@Tag(name = "菜单管理")
@RequestMapping("/menu")
public class MenuController {
    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysRoleMenuService service;
    @GetMapping("/list")
    @Operation(summary = "菜单列表")
    public Result list(){
        List<SysMenu> list=sysMenuService.nodeList();
        return Result.ok(list);
    }
    @PostMapping("/add")
    @Operation(summary = "新增菜单")
    public Result add(@RequestBody SysMenu sysMenu){
        sysMenuService.saveOrUpdate(sysMenu);
        return Result.ok("成功");
    }
    @GetMapping("/remove")
    @Operation(summary = "删除菜单")
    public Result remove(@RequestParam Long id){
        LambdaQueryWrapper<SysMenu> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysMenu::getParentId,id);
        Long count=sysMenuService.count(lambdaQueryWrapper);
        if(count>0){
            return Result.build(500, ResultCodeEnum.Menu_Error);
        }
        sysMenuService.removeById(id);

        return Result.ok("成功");
    }

    @GetMapping("/getrolemenu")
    @Operation(summary = "根据角色获取菜单")
    public Result getroleMenu(@RequestParam Long id){
        LambdaQueryWrapper<SysMenu> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysMenu::getStatus,1);
       //获取所有状态为1的权限
        List<SysMenu> list=sysMenuService.list(lambdaQueryWrapper);
        //根据角色ID获取权限
        LambdaQueryWrapper<SysRoleMenu> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(SysRoleMenu::getRoleId,id);
        List<SysRoleMenu> list1=service.list(lambdaQueryWrapper1);
        List<Long> roleMenuId=new ArrayList<>();
        for (SysRoleMenu sysRoleMenu:list1){
            roleMenuId.add(sysRoleMenu.getMenuId());
        }
        for (SysMenu sysMenu:list){
            if(roleMenuId.contains(sysMenu.getId())){
                sysMenu.setSelect(true);
            }else{
                sysMenu.setSelect(false);
            }
        }
        List<SysMenu> list2= MenuHelper.buildTree(list);
        return Result.ok(list2);
    }
    @PostMapping("/doAssign")
    public Result doAssign(@RequestBody AssginMenuVo assignMenuVo){
        sysMenuService.doAssign(assignMenuVo);
        return Result.ok("成功");
    }
}
